package com.cleverest.cleverestdiary.controller;

import com.cleverest.cleverestdiary.pojo.ArticleCategory;
import com.cleverest.cleverestdiary.pojo.Result;
import com.cleverest.cleverestdiary.service.ArticleCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class ArticleCategoryController {
    @Autowired
    private ArticleCategoryService articleCategoryService;

    @PostMapping
    public Result add(@RequestBody @Validated/*(ArticleCategory.Add.class)*/ ArticleCategory articleCategory) {
        //查询日记分类
        ArticleCategory ac = articleCategoryService.findByArticleCategoryName(articleCategory.getCategoryName());
        if (ac == null) {
            //没有重名
            articleCategoryService.add(articleCategory);
            return Result.success();
        } else {
            //占用
            return Result.error("已经存在该日记分类名");
        }
    }

    @GetMapping
    public Result<List<ArticleCategory>> list() {
        List<ArticleCategory> cs = articleCategoryService.list();
        return Result.success(cs);
    }

    @GetMapping("/detail")
    public Result<ArticleCategory> detail(Integer id) {
        ArticleCategory c = articleCategoryService.findById(id);
        return Result.success(c);
    }

    @PutMapping
    public Result update(@RequestBody @Validated(ArticleCategory.Update.class) ArticleCategory articleCategory) {
        articleCategoryService.update(articleCategory);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(@RequestParam Integer id) {
        ArticleCategory c = articleCategoryService.findById(id);
        if (c == null) {
            return Result.error("找不到这个分类");
        } else {
            articleCategoryService.delete(id);
        }
        return Result.success();
    }
}
